<template>
  <div class="follow-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h2>
            <i class="icon-heart">👥</i>
            收到的关注
          </h2>
          <div class="header-subtitle">发现并管理关注你的用户</div>
        </div>
        <div class="total-count">
          <span class="count-number">{{ totalCount }}</span>
          <span class="count-text">位关注者</span>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <span class="loading-text">加载关注信息中...</span>
    </div>

    <!-- 空状态 -->
    <div v-else-if="follows.length === 0" class="empty-state">
      <div class="empty-icon">
        <i class="icon-empty">👀</i>
      </div>
      <h3 class="empty-title">还没有用户关注你</h3>
      <p class="empty-description">分享你的旅行故事，吸引更多粉丝吧！</p>
      <router-link to="/strategy" class="explore-btn">
        <i class="icon-explore">✍️</i>
        发布攻略
      </router-link>
    </div>

    <!-- 关注列表 - 修改为长条形布局 -->
    <div v-else class="follow-list">
      <div v-for="item in paginatedList" :key="item.followId" class="follow-card">
        <!-- 用户信息区 -->
        <div class="follow-user">
          <router-link :to="`/user/profile/${item.userId}`" class="user-link">
            <img :src="item.userAvatar || defaultAvatar" class="user-avatar" alt="用户头像" />
            <div class="user-info">
              <h3 class="user-name">{{ item.userName }}</h3>
              <div class="follow-time">关注时间: {{ formatDate(item.followedTime) }}</div>
            </div>
          </router-link>
        </div>
        
        <!-- 操作按钮 -->
        <div class="follow-actions">
          <button 
            class="follow-btn" 
            :class="{ 'active': item.isFollowingBack }"
            @click.stop="followBack(item)"
          >
            <i class="follow-icon">{{ item.isFollowingBack ? '✓' : '➕' }}</i>
            <span>{{ item.isFollowingBack ? '已关注' : '回关' }}</span>
          </button>
        </div>
      </div>
    </div>

    <!-- 分页器 -->
    <div v-if="showPagination && follows.length > 0" class="pagination-container">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="totalCount"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import axios from 'axios'

export default {
  name: 'UserFollow',
  setup() {
    const defaultAvatar = ''; 
    const follows = ref([])
    const loading = ref(true)
    const currentUserId = ref(null)
    const totalCount = ref(0)
    const showPagination = ref(true)
    const baseAvatarUrl = 'http://localhost:8080/uploads/avatar/'; 

    const pageSize = ref(5)
    const currentPage = ref(1)

    const paginatedList = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      return follows.value.slice(start, start + pageSize.value)
    })

    // 获取当前用户ID
    const fetchCurrentUserId = async () => {
      const loginId = localStorage.getItem('loginId');
      if (loginId) {
        try {
          const userRes = await axios.get(`http://localhost:8080/mw/UserByLoginId?loginId=${loginId}`);
          currentUserId.value = userRes.data.userId;
          return userRes.data.userId;
        } catch (error) {
          console.error('获取用户ID失败:', error);
          return null;
        }
      }
      return null;
    }

    // 获取关注我的用户列表
    const fetchFollowList = async () => {
      if (!currentUserId.value) return;
      
      loading.value = true;
      try {
        const response = await axios.get(`http://localhost:8080/mw/getFollowers`, {
          params: {
            userId: currentUserId.value
          }
        });
        
        const followersData = response.data.list || response.data;
        totalCount.value = response.data.total || followersData.length;
        
        // 批量检查我是否已经关注了这些用户（互关状态）
        const processedFollows = await Promise.all(
          followersData.map(async (follower) => {
            try {
              // 检查是否已经回关
              const checkRes = await axios.get('http://localhost:8080/mw/checkFollow', {
                params: { 
                  userId: currentUserId.value, 
                  followedUserId: follower.userId 
                }
              });
              
              return {
                followId: follower.followId,
                userId: follower.userId,
                userName: follower.userName || '匿名用户',
                userAvatar: follower.userAvatar ? 
                  (follower.userAvatar.startsWith('http') ? 
                    follower.userAvatar : 
                    baseAvatarUrl + follower.userAvatar) : 
                  defaultAvatar, 
                followedTime: follower.followedTime,
                isFollowingBack: checkRes.data 
              };
            } catch (error) {
              console.error('检查关注状态失败:', error);
              return {
                followId: follower.followId,
                userId: follower.userId,
                userName: follower.userName || '匿名用户',
                userAvatar: follower.userAvatar ? 
                  (follower.userAvatar.startsWith('http') ? 
                    follower.userAvatar : 
                    baseAvatarUrl + follower.userAvatar) : 
                  defaultAvatar,
                followedTime: follower.followedTime,
                isFollowingBack: false
              };
            }
          })
        );
        
        follows.value = processedFollows;
        
      } catch (error) {
        console.error('获取关注列表失败:', error);
        ElNotification.error('获取关注列表失败');
        follows.value = [];
      } finally {
        loading.value = false;
      }
    }

    const handlePageChange = (val) => {
      currentPage.value = val;
    }

    const formatDate = (str) => {
      if (!str) return '';
      try {
        const date = new Date(str);
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
        });
      } catch (error) {
        return str;
      }
    }

    // 回关/取消关注功能
    const followBack = async (user) => {
      if (!currentUserId.value) {
        ElNotification.warning('请先登录');
        return;
      }
      
      if (user.isFollowingBack) {
        // 如果当前是"已关注"状态，则执行取消关注操作
        try {
          const response = await axios.delete(`http://localhost:8080/mw/deleteByUserAndFollow`, {
            params: {
              userId: currentUserId.value, 
              followedUserId: user.userId 
            }
          });
          
          // 根据后端返回的状态码判断是否成功
          if (response.status === 200) { 
            ElMessage.success(`你已取消关注 ${user.userName}`);
            // 更新本地状态
            const index = follows.value.findIndex(f => f.userId === user.userId);
            if (index !== -1) {
              follows.value[index].isFollowingBack = false;
            }
          } else {
            throw new Error('取消关注失败');
          }
        } catch (error) {
          console.error('取消关注失败:', error);
          ElNotification.error('取消关注失败，请稍后再试');
        }
      } else {
        // 如果当前是"回关"状态，则执行回关（添加关注）操作
        try {
          const followData = {
            userId: currentUserId.value,
            followedUserId: user.userId,
            followedTime: new Date().toISOString()
          };
          
          const response = await axios.post(`http://localhost:8080/mw/addUserFollow`, followData);
          
          if (response.data > 0) { 
            ElMessage.success(`你已回关 ${user.userName}`);
            // 更新本地状态
            const index = follows.value.findIndex(f => f.userId === user.userId);
            if (index !== -1) {
              follows.value[index].isFollowingBack = true;
            }
          } else {
            throw new Error('回关失败');
          }
        } catch (error) {
          console.error('回关失败:', error);
          ElNotification.error('回关失败，请稍后再试');
        }
      }
    }

    onMounted(async () => {
      await fetchCurrentUserId();
      if (currentUserId.value) {
        await fetchFollowList();
      } else {
        loading.value = false;
        ElNotification.warning('请先登录查看关注信息');
      }
    })

    return {
      defaultAvatar,
      follows,
      loading,
      totalCount,
      currentPage,
      pageSize,
      showPagination,
      paginatedList,
      handlePageChange,
      formatDate,
      followBack
    }
  }
}
</script>

<style scoped>
.follow-container {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
}

/* 页面头部样式 */
.page-header {
  margin-bottom: 32px;
}

.header-content {
  background: white;
  padding: 24px 32px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left h2 {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.icon-heart {
  font-size: 24px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); }
}

.header-subtitle {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0;
}

.total-count {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: linear-gradient(135deg, #a6a6e4 0%, #c3aadd 100%);
  color: white;
  padding: 16px 20px;
  border-radius: 12px;
  min-width: 80px;
}

.count-number {
  font-size: 24px;
  font-weight: 700;
  line-height: 1;
}

.count-text {
  font-size: 12px;
  opacity: 0.9;
  margin-top: 4px;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.loading-spinner {
  width: 48px;
  height: 48px;
  border: 4px solid #f3f4f6;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 16px;
  color: #6b7280;
  font-weight: 500;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: white;
  border-radius: 16px;
  padding: 60px 40px;
  text-align: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 24px;
  opacity: 0.6;
}

.empty-title {
  font-size: 20px;
  font-weight: 600;
  color: #374151;
  margin: 0 0 12px 0;
}

.empty-description {
  font-size: 16px;
  color: #6b7280;
  margin: 0 0 32px 0;
  line-height: 1.5;
}

.explore-btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px;
  text-decoration: none;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.explore-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}

/* 关注列表 - 修改为长条形布局 */
.follow-list {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
}

.follow-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  position: relative;
  padding: 24px;
  display: grid;
  grid-template-columns: auto 1fr auto;
  gap: 20px;
  align-items: center;
}

.follow-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.follow-user {
  display: flex;
  align-items: center;
  min-width: 200px;
}

.user-link {
  display: flex;
  align-items: center;
  gap: 16px;
  text-decoration: none;
  color: inherit;
}

.user-avatar {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #e2e8f0;
  transition: all 0.3s ease;
}

.user-link:hover .user-avatar {
  border-color: #667eea;
  transform: scale(1.05);
}

.user-info {
  text-align: left;
}

.user-name {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 4px 0;
}

.follow-time {
  font-size: 12px;
  color: #9ca3af;
}

/* 操作按钮 */
.follow-actions {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.follow-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background: linear-gradient(135deg, #4CAF50 0%, #2E7D32 100%);
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 10px rgba(46, 125, 50, 0.3);
}

.follow-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(46, 125, 50, 0.5);
}

.follow-btn.active {
  background: linear-gradient(135deg, #9E9E9E 0%, #616161 100%);
  cursor: default;
}

.follow-icon {
  font-size: 14px;
}

/* 分页器 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .follow-container {
    padding: 16px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .follow-card {
    grid-template-columns: 1fr;
    gap: 16px;
    padding: 20px;
  }
  
  .follow-user {
    flex-direction: row;
    align-items: center;
    gap: 16px;
  }
  
  .user-link {
    flex-direction: row;
    text-align: left;
  }
  
  .user-avatar {
    width: 48px;
    height: 48px;
  }
  
  .follow-actions {
    align-items: flex-start;
  }
}

@media (max-width: 480px) {
  .header-content {
    padding: 20px;
  }
  
  .header-left h2 {
    font-size: 24px;
  }
}
</style>